import React from 'react';
import { Input, Select, message } from 'antd';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import * as routerActions from 'react-router-redux';
import { mapConfig } from 'Constants/config';
import { BROWSER_MODE } from 'Constants/webConstants';
import TitleButton from 'Component/Page/Components/TitleButton';
import './shianMap.scss';

const Search = Input.Search;
const Option = Select.Option;

const MAP_BUSINESS_TYPE_ICONS = [
  {
    label: '食品流通',
    alert_level1: 'images/mapIcon/icon_food_circular1.png',
    alert_level2: 'images/mapIcon/icon_food_circular2.png',
    alert_level3: 'images/mapIcon/icon_food_circular3.png',
    alert_normal: 'images/mapIcon/icon_food_circular_normal.png',
  },
  {
    label: '餐饮服务',
    alert_level1: 'images/mapIcon/icon_catering_service1.png',
    alert_level2: 'images/mapIcon/icon_catering_service2.png',
    alert_level3: 'images/mapIcon/icon_catering_service3.png',
    alert_normal: 'images/mapIcon/icon_catering_service.png',
  },
  {
    label: '食品生产',
    alert_level1: 'images/mapIcon/icon_food_production1.png',
    alert_level2: 'images/mapIcon/icon_food_production2.png',
    alert_level3: 'images/mapIcon/icon_food_production3.png',
    alert_normal: 'images/mapIcon/icon_food_production.png',
  },
  {
    label: '药品经营',
    alert_level1: 'images/mapIcon/icon_medicine_manage1.png',
    alert_level2: 'images/mapIcon/icon_medicine_manage2.png',
    alert_level3: 'images/mapIcon/icon_medicine_manage3.png',
    alert_normal: 'images/mapIcon/icon_medicine_manage.png',
  },
  {
    label: '保健食品',
    alert_level1: 'images/mapIcon/icon_health_medicine1.png',
    alert_level2: 'images/mapIcon/icon_health_medicine2.png',
    alert_level3: 'images/mapIcon/icon_health_medicine3.png',
    alert_normal: 'images/mapIcon/icon_health_medicine.png',
  },
  {
    label: '化妆品',
    alert_level1: 'images/mapIcon/icon_makeup1.png',
    alert_level2: 'images/mapIcon/icon_makeup2.png',
    alert_level3: 'images/mapIcon/icon_makeup3.png',
    alert_normal: 'images/mapIcon/icon_makeup.png',
  },
  {
    label: '医疗器械',
    alert_level1: 'images/mapIcon/icon_midical_instrucment1.png',
    alert_level2: 'images/mapIcon/icon_midical_instrucment2.png',
    alert_level3: 'images/mapIcon/icon_midical_instrucment3.png',
    alert_normal: 'images/mapIcon/icon_midical_instrucment.png',
  },
];
const MAP_ALERT_LEVEL = [
  {
    key: '1',
    label: '预警'
  },
  {
    key: '2',
    label: '警示'
  },
  {
    key: '3',
    label: '告警'
  },
  {
    key: '4',
    label: '正常'
  }
];
class ShiAnMap extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      zoom: 18, //地图级别,
      data: [],
      searchValue: '',
      alertLevel: '',
      deptData: [],
      typeName: '',
      selectDept: '',
      currentInfoWin: '',
      videoChecked: true
    };
    this.initMap = ::this.initMap;
    this.onLoad = ::this.onLoad;
    this.getIconUrl = ::this.getIconUrl;
  }
  componentDidMount() {
    this.initMap();
    this.initDeptData();
    this.initVideoStatus();
  }
  getIconUrl(data) {
    const selectedBusinessType = MAP_BUSINESS_TYPE_ICONS.filter(item => item.label === data.category)[0];
    let url = '';
    const alertLevel = parseInt(data.level, 10);
    if (alertLevel === parseInt(MAP_ALERT_LEVEL[0].key, 10)) {
      url = selectedBusinessType.alert_level1;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[1].key, 10)) {
      url = selectedBusinessType.alert_level2;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[2].key, 10)) {
      url = selectedBusinessType.alert_level3;
    } else if (alertLevel === parseInt(MAP_ALERT_LEVEL[3].key, 10)) {
      url = selectedBusinessType.alert_normal;
    }
    return url;
  }
  initVideoStatus() {
    const api = new Api({
      method: 'GET',
      path: '/switch_maps/sun_kitchen',
      success: (res) => {
        this.setState({
          videoChecked: res.switch_value
        });
      }
    });
    api.run();
  }
  initMap() {
    //经纬度地图显示；
    this.map = new T.Map('mapDiv');
    //双击放大地图；
    this.map.enableDoubleClickZoom();
    //地图滚轮缩放；
    this.map.enableScrollWheelZoom();
    //地图惯性拖拽；
    this.map.enableInertia();
    //创建缩放平移控件对象
    const control = new T.Control.Zoom();
    //创建比例尺控件对象
    const scale = new T.Control.Scale();
    //添加比例尺控件
    this.map.addControl(scale);
    //添加缩放平移控件
    this.map.addControl(control);
    control.setPosition(T_ANCHOR_BOTTOM_RIGHT);
    //设置显示地图的中心点和级别
    this.map.centerAndZoom(new T.LngLat(mapConfig.longitude, mapConfig.latitude), this.state.zoom);
  }
  initDeptData() {
    const api = new Api({
      method: 'GET',
      path: '/justices/dept',
      success: (res) => {
        this.setState({
          deptData: res,
        }, () => {
          this.initSearchBusiness();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initSearchBusiness() {
    const { searchValue, alertLevel, selectDept, typeName } = this.state;
    console.log(searchValue, alertLevel, selectDept, typeName);
    const query = {};
    query.offset = 0;
    query.limit = 10000;
    if (selectDept) { query.manage_gov_id = selectDept; }
    if (typeName) { query.category = typeName; }
    if (alertLevel) { query.level = alertLevel; }
    if (searchValue) { query.name_like = searchValue; }
    const api = new Api({
      method: 'GET',
      path: '/enterprises/warn_level',
      query,
      success: (res) => {
        this.setState({
          data: res.data_list
        }, () => {
          if (searchValue && res.data_list.length > 0) {
            /*当有搜索的时候，地图中心以搜索的数据取中心*/
            const data = res.data_list.map(item => new T.LngLat(item.longitude, item.latitude));
            const newData = this.map.getViewport(data);
            this.map.panTo(new T.LngLat(newData.center.lng, newData.center.lat), newData.zoom);
          }
          this.onLoad();
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onLoad() {
    const self = this;
    const { data, videoChecked } = this.state;
    this.map.clearOverLays();
    for (let i = 0; i < data.length; i++) {
      const icon1 = new T.Icon({ iconUrl: self.getIconUrl(data[i]), iconSize: new T.Point(36, 36), iconAnchor: new T.Point(18, 36) });
      const iconCamera = new T.Icon({ iconUrl: 'images/icon_video_camera.png', iconSize: new T.Point(30, 36), iconAnchor: new T.Point(15, 36) });
      //向地图上添加自定义标注
      const marker1 = new T.Marker(new T.LngLat(data[i].longitude, data[i].latitude), { icon: data[i].sun_kitchens.length > 0 ? iconCamera : icon1 });
      this.map.addOverLay(marker1);
      //add title
      // icon click
      marker1.addEventListener('click', () => {
        this.map.removeOverLay(this.state.currentInfoWin); //清除地图上当前打开的infowin
        this.infoWin = new T.InfoWindow();
        const lnglat = new T.LngLat(data[i].longitude, data[i].latitude);
        this.map.panTo(new T.LngLat(data[i].longitude, data[i].latitude), this.map.getZoom());
        this.infoWin.setLngLat(lnglat);
        this.infoWin.setOffset([0, -36]);
        const cameraImg = data[i].sun_kitchens.length > 0 ? `<img src="images/icons/icon_video.png" alt="视频" class="video_kitchen" id=${`${data[i].id}`}>` : '';
        let levelObj = '';
        if (parseInt(data[i].level, 10) === 1) {
          levelObj = `<span class="level1">${'预警'}</span>`;
        } else if (parseInt(data[i].level, 10) === 2) {
          levelObj = `<span class="level2">${'警示'}</span>`;
        } else if (parseInt(data[i].level, 10) === 3) {
          levelObj = `<span class="level3">${'告警'}</span>`;
        } else if (parseInt(data[i].level, 10) === 4) {
          levelObj = `<span class="normal">${'正常'}</span>`;
        }
        this.infoContent = `<ul >
                        <li>
                        <div>
                        <img src="images/icons/icon_hotel.png" alt="酒店" class="win-hotel">
                        <div>${data[i].name || ''}</div>
                        </div>
                        </li>
                        <li>${data[i].address || ''}</li>
                        <li>法人代表：${data[i].legal_entity || ''}</li>
                        <li>消费提示：${levelObj}</li>
                        <li>${videoChecked ? cameraImg : ''}</li>
                        </ul>`;
        this.infoWin.setContent(this.infoContent);
        //向地图上添加信息窗口
        this.map.addOverLay(this.infoWin);
        this.setState({
          currentInfoWin: this.infoWin
        });
        if (cameraImg) {
          document.getElementById(`${data[i].id}`).onclick = (e) => {
            this.props.dispatch(routerActions.push(`/server/sun_kitchen/${data[i].id}`));
            e.stopPropagation();
          };
        }
      }, false);
    }
  }

  handleSearch(value) {
    this.setState({
      searchValue: value.trim()
    }, () => {
      this.initSearchBusiness();
    });
  }
  handleAlert(key) {
    this.setState({
      alertLevel: key ? parseInt(key, 10) : ''
    }, () => {
      this.initSearchBusiness();
    });
  }
  handleDeptChange(e) {
    this.setState({
      selectDept: e.toString(),
    }, () => {
      this.initSearchBusiness();
    });
  }
  handleTypeChange(e) {
    this.setState({
      typeName: e || ''
    }, () => {
      this.initSearchBusiness();
    });
  }
  handleSelectDept(v, e) {
    if (e.props.item) {
      this.map.panTo(new T.LngLat(e.props.item.longitude, e.props.item.latitude), this.state.zoom);
    } else {
      this.map.panTo(new T.LngLat(mapConfig.longitude, mapConfig.latitude), this.state.zoom);
    }
  }
  render() {
    const { deptData, selectDept, typeName, alertLevel } = this.state;
    const { mode } = this.props;
    const isVertical = BROWSER_MODE.isVertical(mode);
    if (isVertical) {
      return (
        <div className="v-map-container">
          <div className="main-map" >
            <div className="map-header" >
              <TitleButton title="食安地图" />
              <div className="header-right" >
                <Select
                  placeholder="请选择区域"
                  className="select"
                  value={selectDept}
                  onChange={this.handleDeptChange.bind(this)}
                  onSelect={this.handleSelectDept.bind(this)}
                >
                  <Option key={''} value={''} >全县</Option >
                  {
                    deptData.length > 0 ? deptData.map(item => <Option key={item.id.toString()} item={item} >{item.name}</Option >) : ''
                  }
                </Select >
                <Select placeholder="请选择企业类型" className="select" value={typeName} onChange={this.handleTypeChange.bind(this)}>
                  <Option key={''} value={''} >所有</Option >
                  {
                    MAP_BUSINESS_TYPE_ICONS.map(item => (
                      <Option key={item.label} >{item.label}</Option >
                    ))
                  }
                </Select >
                <Select placeholder="请选择" className="select" value={alertLevel.toString()} onSelect={this.handleAlert.bind(this)} >
                  <Option key={''} value={''} >所有</Option >
                  {
                    MAP_ALERT_LEVEL.map(item => (
                      <Option key={item.key} >{item.label}</Option >
                    ))
                  }
                </Select >
                <Search placeholder="搜索" className="map-search" onSearch={this.handleSearch.bind(this)} />
              </div >
            </div >
            <div className="map" >
              <div id="mapDiv" />
            </div >
          </div >
        </div >
      );
    }
    return (
      <div className="map-container">
        <div className="main-map" >
          <div className="map-header" >
            <TitleButton title="食安地图" />
            <div className="header-right" >
              <Select
                placeholder="请选择区域"
                className="select"
                value={selectDept}
                onChange={this.handleDeptChange.bind(this)}
                onSelect={this.handleSelectDept.bind(this)}
              >
                <Option key={''} value={''} >全县</Option >
                {
                  deptData.length > 0 ? deptData.map(item => <Option key={item.id.toString()} item={item} >{item.name}</Option >) : ''
                }
              </Select >
              <Select placeholder="请选择企业类型" className="select" value={typeName} onChange={this.handleTypeChange.bind(this)}>
                <Option key={''} value={''} >所有</Option >
                {
                  MAP_BUSINESS_TYPE_ICONS.map(item => (
                    <Option key={item.label} >{item.label}</Option >
                  ))
                }
              </Select >
              <Select placeholder="请选择" className="select" value={alertLevel.toString()} onSelect={this.handleAlert.bind(this)} >
                <Option key={''} value={''} >所有</Option >
                {
                  MAP_ALERT_LEVEL.map(item => (
                    <Option key={item.key} >{item.label}</Option >
                  ))
                }
              </Select >
              <Search placeholder="搜索" className="map-search" onSearch={this.handleSearch.bind(this)} />
            </div >
          </div >
          <div className="map" >
            <div id="mapDiv" />
          </div >
        </div >
      </div >
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.webReducer,
    ...state.routing
  };
}

export default connect(mapStateToProps)(ShiAnMap);

